Java version of the sequential sum algorithm or n(n+1)/2
My first Android homework was to write a little program that would add sequential numbers such as 1 to 100. I call it a Sequential Sum, but I couldn’t find the exact mathematical name.
You can read more about this mathematical task here: Techniques for adding the numbers 1 to 100
In code, you could of course loop through 1 through 100 and += them into a value but there is a more efficient way and most everyone in my class mentioned that is what they did, so I guess I was unique in choosing this solution.
Or you could use the following equation that provides you the answer to get the sum of all numbers between 1 and the end value, n.
n(n+1)/2
Now what if you aren’t starting at 1? What if you want to add the numbers between 50 and 150? Well, this is easy. The last number before the start value of 50 is 49 or 50 – 1 = 49. We can get the value of 1 to 49 and subtract it from the value of 1 to 150.
n(n+1)/2 – s(s+1)/2
While this is for Android, it is basically just java and there is nothing Android specific here. Here is my class.
package org.jaredbarneck.cs6890; import java.security.InvalidParameterException; /** * @author Jared * */ public class SequentialSum { // Member variables private int _LowValue = 0; private int _HighValue = 0; // Constructors public SequentialSum(int inLowValue, int inHighValue) { SetHighValue(inHighValue); SetLowValue(inLowValue); } // Getters and Setters public int GetLowValue() { return _LowValue; } public int GetHighValue() { return _HighValue; } public void SetLowValue(int inValue) { if (inValue < 0) throw new InvalidParameterException( "Value must be greater than zero!"); if (inValue > _HighValue) throw new InvalidParameterException( "High value must be lower than the high value!"); _LowValue = inValue; } public void SetHighValue(int inValue) { if (inValue < 0) throw new InvalidParameterException( "Value must be greater than zero!"); if (inValue < _LowValue) throw new InvalidParameterException( "High value must be greater than the low value!"); _HighValue = inValue; } // Methods public int Sum() { int sumToSubtract = 0; if (_LowValue > 1) { int tmpVal = _LowValue - 1; sumToSubtract = tmpVal * (tmpVal + 1) / 2; } return (_HighValue * (_HighValue + 1) / 2) - sumToSubtract; } }
So if I ever need to get the sum of all values between a sequential list of numbers, I can come back and use this class again.
Note: No, I don’t follow java syntax rules and no, I don’t plan too either. I don’t start anything with lower case that is not a local variable. My member variables start with an underscore _ and then an uppercase letter. Everything else starts with upper case. I don’t conform my style to a specific language’s style, instead I try to use the same style in all languages.